package com.zsj.juc.completableFuture;

import java.util.concurrent.*;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/4/18 18:37
 * @description 为Future接口的升级
 */
public class CompletableFutureTest02 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);

        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("1秒后出结果" + result);
            return result;
        }, threadPool).whenComplete((v, e) -> {
            if (e == null) {
                System.out.println(Thread.currentThread().getName() + "come in");
                System.out.println("计算完成");
                System.out.println("当前v=" + v);
            }
        }).exceptionally(e -> {
            e.printStackTrace();
            System.out.println("异常情况" + e.getCause() + e.getMessage());
            return null;
        });

        System.out.println(Thread.currentThread().getName() + "继续做事情");
//        try {TimeUnit.MILLISECONDS.sleep(3000);}catch (InterruptedException e){e.printStackTrace();}

        threadPool.shutdown();
    }

    private static void simple() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("1秒后出结果" + result);
            return result;
        });

        System.out.println(completableFuture.get());
    }
}
